#!/bin/bash

echo "=== Cursor MCP 配置修复脚本 ==="

# 检测操作系统
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    CURSOR_CONFIG_DIR="$HOME/Library/Application Support/Cursor/User"
    CURSOR_CONFIG_FILE="$CURSOR_CONFIG_DIR/settings.json"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    CURSOR_CONFIG_DIR="$HOME/.config/Cursor/User"
    CURSOR_CONFIG_FILE="$CURSOR_CONFIG_DIR/settings.json"
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
    # Windows
    CURSOR_CONFIG_DIR="$APPDATA/Cursor/User"
    CURSOR_CONFIG_FILE="$CURSOR_CONFIG_DIR/settings.json"
else
    echo "❌ 不支持的操作系统: $OSTYPE"
    exit 1
fi

echo "📁 Cursor配置目录: $CURSOR_CONFIG_DIR"
echo "📄 配置文件: $CURSOR_CONFIG_FILE"

# 检查配置文件是否存在
if [ ! -f "$CURSOR_CONFIG_FILE" ]; then
    echo "📝 创建新的配置文件..."
    mkdir -p "$CURSOR_CONFIG_DIR"
    echo '{}' > "$CURSOR_CONFIG_FILE"
fi

# 备份原配置文件
BACKUP_FILE="$CURSOR_CONFIG_FILE.backup.$(date +%Y%m%d_%H%M%S)"
cp "$CURSOR_CONFIG_FILE" "$BACKUP_FILE"
echo "💾 已备份原配置文件到: $BACKUP_FILE"

echo "🔧 尝试多种MCP配置格式..."

# 方法1: 标准MCP配置
echo "📝 方法1: 标准MCP配置..."
python3 -c "
import json
import sys

try:
    with open('$CURSOR_CONFIG_FILE', 'r', encoding='utf-8') as f:
        config = json.load(f)
    
    # 清除旧的MCP配置
    if 'mcp.servers' in config:
        del config['mcp.servers']
    if 'mcpServers' in config:
        del config['mcpServers']
    
    # 添加新的MCP配置
    config['mcp.servers'] = {
        'mysql': {
            'type': 'http',
            'url': 'http://localhost:8099/mcp/call',
            'headers': {
                'Content-Type': 'application/json'
            }
        }
    }
    
    with open('$CURSOR_CONFIG_FILE', 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
    
    print('✅ 方法1配置已应用')
    
except Exception as e:
    print(f'❌ 方法1失败: {e}')
"

echo ""
echo "🔄 请重启Cursor并测试..."
echo "如果还是不行，我们将尝试其他配置方法"
echo ""
echo "📋 测试步骤："
echo "1. 重启Cursor"
echo "2. 打开命令面板 (Cmd/Ctrl + Shift + P)"
echo "3. 搜索 'MCP' 或 'Model Context Protocol'"
echo "4. 查看是否有可用的MCP工具"
echo ""
echo "🧪 如果还是不行，请运行："
echo "./cursor-mcp-fix.sh method2" 